package com.demo.webapp.filter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;

import com.demo.common.StringUtils;
import com.demo.core.model.SiteFunction;
import com.demo.webapp.config.Constants;
import com.demo.webapp.context.MultisiteContextHolder;

/**
 * 安全上下文请求的封装对象
 * 
 * @author ryuu.kk  at 2013-04-08
 */
public class SecurityContextHolderAwareRequestWrapper extends org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper  {

	private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
	
	/**
     * 当前用户的角色列表
     */
    private List<String> roleList;
    
    /**
     * 功能列表
     */
    private Map<String, Map<Long, SiteFunction>> functionMap;
    
	@SuppressWarnings("unchecked")
	public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix) {
		
		super(request, rolePrefix);
		
		ServletContext servletContext = getSession().getServletContext();
		
        roleList = new ArrayList<String>();
		// 得到APP启动的配置Map
		Map<String, Object> configMap = (Map<String, Object>) servletContext.getAttribute(Constants.CONFIG);
		Assert.notNull(configMap);
		if (configMap != null) {
			functionMap = (Map<String, Map<Long, SiteFunction>>) configMap.get(Constants.CONFIG_FUNCTION_ACL);
		}
		Authentication authentication = getAuthentication();
		if (authentication != null) {
			Iterator<? extends GrantedAuthority> iterator = authentication.getAuthorities().iterator();
			while(iterator != null && iterator.hasNext()) {
				roleList.add(iterator.next().getAuthority());
			}
		}
	}
	
    @Override
	public boolean isUserInRole(String role) {

		boolean isPermission = false;
		isPermission = super.isUserInRole(role);

		if (!isPermission) {
			String siteName = MultisiteContextHolder.getSite().getDomain();
			if (functionMap != null) {
				if (StringUtils.isNotEmpty(siteName)) {
					Map<Long, SiteFunction> siteFunctionMap = functionMap.get(siteName);
					if (siteFunctionMap != null) {
						if (StringUtils.isNumber(role)) {
							SiteFunction sf = siteFunctionMap.get(Long.parseLong(role));
							if (sf != null) {
								for (String r : sf.getRoleList()) {
									if (roleList.contains(r)) {
										return true;
									}
								}
							}
						}
					} else {
						// 站点不存在安全访问列表
						
					}
				}
			}
		}
		return isPermission;
	}
    
    private Authentication getAuthentication() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (!authenticationTrustResolver.isAnonymous(auth)) {
            return auth;
        }

        return null;
    }
}
